package com.jingdianjichi.wx.ai;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisAnswerCache implements AnswerCache {

    private final StringRedisTemplate redis;

    @Autowired
    public RedisAnswerCache(StringRedisTemplate redis) { this.redis = redis; }

    private String k(String qKey){ return "qa:ans:" + qKey; }

    @Override
    public String getByQuestionKey(String qKey) {
        try { return redis.opsForValue().get(k(qKey)); } catch (Exception e){ return null; }
    }

    @Override
    public void put(String qKey, String answer, long ttlSeconds) {
        try { redis.opsForValue().set(k(qKey), answer, ttlSeconds, TimeUnit.SECONDS); } catch (Exception ignored) {}
    }
}
